package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component("springSecurityService")
public class SpringSecurityService implements UserDetailsService {

   @Reference
   private UserService userService;

   //通过用户名获取用户的详细信息(密码和权限列表)
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      int a;

      //1.通过用户名查询用户数据(详细信息,包括角色列表,和权限列表)
      User user = userService.findByUsername(username);
      if (user == null) {
         return null;
      }
      //2.给用户授权
      List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
      Set<Role> roles = user.getRoles();
      if (roles != null && roles.size() > 0) {
         for (Role role : roles) {
            //2.1遍历roles,授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));//授予角色
            Set<Permission> permissions = role.getPermissions();
            //2.2遍历permissions,授予权限
            if (permissions != null && permissions.size() > 0) {
               for (Permission permission : permissions) {
                  list.add(new SimpleGrantedAuthority(permission.getKeyword()));//授予权限
               }
            }

         }
      }


      //3.返回用户详情对象
      UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);

      return userDetails;
   }
}
